package com.ojoin.trade.supplyloan_core.web.service.impl;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.message.BufferedHeader;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;

import com.ojoin.trade.common.Constants;
import com.ojoin.trade.common.utils.json.JSONUtils;

public class WoMaiTest {

	private static String userName = "991761";
	private static String password = "d2092538eb8a24abac143817f1f5f880"; // huan220&&&

	// 处理结算单
	private static String redirectURL = "http://supplier.i.womaiapp.com/statement/queryStatementList.action";

	// 登陆
	private static String loginURL = "http://passport.womaiapp.com/login";
	
	private static String imageUrl = "http://passport.womaiapp.com/captcha.jpg";
	private static String image_save_path = "c://captcha.png";

	private HttpResponse response;
	private DefaultHttpClient httpclient = new DefaultHttpClient();

	public static void main(String[] args) {
		try {
			WoMaiTest service = new WoMaiTest();
			if (service.login()) {
				System.out.println(service.getText(redirectURL));
				String redirectLocation = service.getRedirectLocation();
				if (redirectLocation != null) {
					System.out.println(service.getText(redirectLocation));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean login() throws Exception {
		Map map = getParams();

		HttpPost httpost = new HttpPost(loginURL);
		List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
		nvps.add(new BasicNameValuePair("ReturnUrl", redirectURL));
		nvps.add(new BasicNameValuePair("username", userName));
		nvps.add(new BasicNameValuePair("password", password));

		String cookie = getImgCookie();// 存储图片并获得get的cookie
		String vetifyCode = getVetifyCode(image_save_path);
		nvps.add(new BasicNameValuePair("captcha", vetifyCode));

		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next().toString();
			String value = map.get(key).toString();
			nvps.add(new BasicNameValuePair(key, value));
		}

		try {
			httpost.setEntity(new UrlEncodedFormEntity(
					(List<? extends org.apache.http.NameValuePair>) nvps,
					HTTP.UTF_8));
			httpost.setHeader("Cookie", cookie);
			httpost.setHeader("Host", "passport.womaiapp.com");
			httpost.setHeader("Origin", "http://passport.womaiapp.com");
			httpost.setHeader("Referer", "http://www.womai.com");
			httpost.setHeader(
					"User-Agent",
					"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36 CoolNovo/2.0.9.19");
			response = httpclient.execute(httpost);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			httpost.abort();
		}
		return true;
	}

	private String getImgCookie() throws IOException, ClientProtocolException {
		httpclient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
		HttpGet httpGet = new HttpGet(imageUrl);
		httpGet.getParams()
				.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
		HttpResponse response = httpclient.execute(httpGet);
		download(response.getEntity().getContent(), image_save_path);
		List<Cookie> cookies = httpclient.getCookieStore().getCookies();
		httpGet.releaseConnection();
		StringBuilder cookiesSB = new StringBuilder();
		System.out.println("第一次cookie");
		if (cookies.isEmpty()) {
			System.out.println("None");
		} else {
			for (int i = 0; i < cookies.size(); i++) {
				// System.out.println("- " + cookies.get(i).toString());
				cookiesSB.append(cookies.get(i).getName()).append("=")
						.append(cookies.get(i).getValue()).append("; ");
			}
		}

		String cookie = cookiesSB.toString();
		return cookie;
	}

	public Map<String, String> getParams() {
		Map<String, String> map = new HashMap<String, String>();
		String str = getText(loginURL);

		String lt_1[] = str.split("name=\"lt\" value=\"");
		String lt_2[] = lt_1[1].split("\"/>");
		String lt = lt_2[0];
		map.put("lt", lt);

		String execution_1[] = str.split("name=\"execution\" value=\"");
		String execution_2[] = execution_1[1].split("\"/>");
		String execution = execution_2[0];
		map.put("execution", execution);
		map.put("_eventId", "submit");

		return map;
	}

	private String getText(String redirectLocation) {
		HttpGet httpget = new HttpGet(redirectLocation);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String responseBody = "";
		try {
			responseBody = httpclient.execute(httpget, responseHandler);
		} catch (Exception e) {
			e.printStackTrace();
			responseBody = null;
		} finally {
			httpget.abort();
			// httpclient.getConnectionManager().shutdown();
		}
		return responseBody;
	}

	private String getRedirectLocation() {
		BufferedHeader locationHeader = (BufferedHeader) response
				.getFirstHeader("Location");
		if (locationHeader == null) {
			return null;
		}
		return locationHeader.getValue();
	}

	public String getVetifyCode(String filename) {
		try {
			// 换行符
			final String newLine = "\r\n";
			final String boundaryPrefix = "--";
			// 定义数据分隔线
			String BOUNDARY = "----WebKitFormBoundaryKyy2rsC4lOW6tnIw";
			// 服务器的域名
			URL url = new URL(
					"http://bbb4.hyslt.com/api.php?mod=php&act=upload");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置为POST情
			conn.setRequestMethod("POST");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// 设置请求头参数
			conn.setRequestProperty("Host", "bbb4.hyslt.com");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Charsert", Constants.ENCODING);
			conn.setRequestProperty(
					"User-Agent",
					"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36");
			conn.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);
			OutputStream out = new DataOutputStream(conn.getOutputStream());
			StringBuilder sb = new StringBuilder();
			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"user_name\""
					+ newLine);
			sb.append(newLine);
			sb.append("18join" + newLine);

			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"user_pw\""
					+ newLine);
			sb.append(newLine);
			sb.append("13572468" + newLine);

			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"yzm_minlen\""
					+ newLine);
			sb.append(newLine);
			sb.append("5" + newLine);

			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"yzm_maxlen\""
					+ newLine);
			sb.append(newLine);
			sb.append("5" + newLine);

			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"yzmtype_mark\""
					+ newLine);
			sb.append(newLine);
			sb.append("25" + newLine);

			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"zztool_token\""
					+ newLine);
			sb.append(newLine);
			sb.append("" + newLine);

			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append("Content-Disposition: form-data;name=\"upload\"; filename=\"1.jpg\""
					+ newLine);
			sb.append("Content-Type: image/jpeg" + newLine);
			sb.append(newLine);
			System.out.println("Request body:\n" + sb.toString() + "\n");
			// 将参数头的数据写入到输出流中
			out.write(sb.toString().getBytes());

			// // 通过url读取womai的验证码图片信息，new一个URL对象
			// URL imgurl = new URL(imageUrl);
			// // 打开链接
			// HttpURLConnection imgconn = (HttpURLConnection) imgurl
			// .openConnection();
			// // 设置请求方式为"GET"
			// imgconn.setRequestMethod("GET");
			// // 超时响应时间为5秒
			// imgconn.setConnectTimeout(5 * 1000);
			// // 通过输入流获取图片数据
			// InputStream inStream = imgconn.getInputStream();
			// DataInputStream in = new DataInputStream(inStream);

			File file = new File(filename);
			// 数据输入流,用于读取文件数据
			DataInputStream in = new DataInputStream(new FileInputStream(file));
			byte[] bufferOut = new byte[1024];
			int bytes = 0;
			while ((bytes = in.read(bufferOut)) != -1) {
				out.write(bufferOut, 0, bytes);
			}
			out.write(newLine.getBytes());
			in.close();
			// 定义最后数据分隔线，即--加上BOUNDARY再加上--。
			byte[] end_data = (newLine + boundaryPrefix + BOUNDARY
					+ boundaryPrefix + newLine).getBytes();
			// 写上结尾标识
			out.write(end_data);
			out.flush();
			out.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				// String jsonStr =
				// "{\"result\":true,\"data\":{\"id\":6663538441,\"val\":\"GNWF8\"}}";
				HashMap jsonMap = (HashMap) JSONUtils.parseObject(line,
						Map.class);
				HashMap jsonMap2 = (HashMap) jsonMap.get("data");
				String val = (String) jsonMap2.get("val");
				if (val != null)
					return val;
				// System.out.println(val);
			}
			return line;
		} catch (Exception e) {
			System.out.println("发送POST请求出现异常！" + e);
			e.printStackTrace();
		}
		return null;
	}

	public byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		// 创建一个Buffer字符串
		byte[] buffer = new byte[1024];
		// 每次读取的字符串长度，如果为-1，代表全部读取完毕
		int len = 0;
		// 使用一个输入流从buffer里把数据读取出来
		while ((len = inStream.read(buffer)) != -1) {
			// 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
			outStream.write(buffer, 0, len);
		}
		// 关闭输入流
		inStream.close();
		// 把outStream里的数据写入内存
		return outStream.toByteArray();
	}

	public boolean download(InputStream in, String path) {
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(path);
			byte b[] = new byte[1024];
			int j = 0;
			while ((j = in.read(b)) != -1) {
				out.write(b, 0, j);
			}
			out.flush();
			File file = new File(path);
			if (file.exists() && file.length() == 0)
				return false;
			return true;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			if ("FileNotFoundException".equals(e.getClass().getSimpleName()))
				System.err.println("download FileNotFoundException");
			if ("SocketTimeoutException".equals(e.getClass().getSimpleName()))
				System.err.println("download SocketTimeoutException");
			else
				e.printStackTrace();
		} finally {

			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return false;
	}

	/**
	 * 采集
	 * 
	 * @param url
	 *            ：指定URL
	 * @param times
	 *            ：如果采集失败，采集最少次数（2次）
	 * @return
	 */
	public static boolean download(String urlstr, String path) {
		if (urlstr == null || "".equals(urlstr.trim()))
			return false;

		InputStream in = null;
		FileOutputStream out = null;
		try {
			System.out.println("download url " + urlstr);
			URL url = new URL(urlstr);
			URLConnection connection = url.openConnection();
			connection.setConnectTimeout(5000);// jdk 1.5换成这个,连接超时
			// connection.setReadTimeout(5000);//jdk 1.5换成这个,读操作超时
			connection.setDoOutput(true);

			out = new FileOutputStream(path);
			in = connection.getInputStream();
			byte b[] = new byte[1024];
			int j = 0;
			while ((j = in.read(b)) != -1) {
				out.write(b, 0, j);
			}
			out.flush();
			File file = new File(path);
			if (file.exists() && file.length() == 0)
				return false;
			return true;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			if ("FileNotFoundException".equals(e.getClass().getSimpleName()))
				System.err.println("download FileNotFoundException");
			if ("SocketTimeoutException".equals(e.getClass().getSimpleName()))
				System.err.println("download SocketTimeoutException");
			else
				e.printStackTrace();
		} finally {
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return false;
	}
}
